package service

import (
	"barrage-go/common"
	"barrage-go/consts"
	"barrage-go/models"
	"barrage-go/proto/pb"
	"barrage-go/utils"
	"github.com/golang/protobuf/proto"
	"github.com/gorilla/websocket"
	"log"
)

func WebClientLoginReq(msg []byte, ws *websocket.Conn) {

	loginReq := pb.WebClientLoginReq{}
	err := proto.Unmarshal(msg, &loginReq)
	if err != nil {
		log.Panicln("客户端登录发生异常:", err)
	}

	videoId := loginReq.VideoId
	if videoId == "" {
		log.Println("解析出来的视频id为空")
		return
	}

	common.AddClient(videoId, ws)
	barrageOnlineCount := utils.Incr(consts.BarrageOnlinePopulation + videoId)
	barrageTotalWatch := utils.Incr(consts.BarrageTotalWatch + videoId)

	loginResp := pb.WebClientLoginResp{
		BarrageTotalCount:      models.GetBarrageTotalCount(videoId),
		BarrageOnlineCount:     int32(barrageOnlineCount),
		BarrageTotalWatchCount: int32(barrageTotalWatch),
	}

	loginRespBytes, _ := proto.Marshal(&loginResp)
	clientResp := pb.Barrage{
		MsgType:   consts.WebClientLoginResp,
		BytesData: loginRespBytes,
	}

	client, _ := proto.Marshal(&clientResp)
	err = ws.WriteMessage(websocket.BinaryMessage, client)
	if err != nil {
		log.Println("返回给客户端登录信息结果发生异常:", err)
	}

}
